/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.otod.web;

import com.otod.entity.Min;
import com.otod.entity.Quote;
import com.otod.entity.Stock;
import com.otod.entity.Trade;
import com.otod.service.StockService;
import com.otod.tools.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/")
public class MainController {

    public static String FAILSTRING = "0";
    public static String SUCCESSSTRING = "1";

    @Autowired
    private StockService stockService;

    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("stocks", stockService.getAllStock());
        model.addAttribute("traders", stockService.getAllTrader());
        return "main";
    }

    @RequestMapping(value = "trade", method = RequestMethod.GET)
    public String trading(Model model) {
        model.addAttribute("stocks", stockService.getAllStock());
        model.addAttribute("traders", stockService.getAllTrader());
        return "trading";
    }

    @RequestMapping(value = "trader", method = RequestMethod.GET)
    public String trader(Model model) {
        model.addAttribute("stocks", stockService.getAllStock());
        model.addAttribute("traders", stockService.getAllTrader());
        return "trader";
    }


    @RequestMapping(value = "trade/save", method = RequestMethod.POST)
    public String trade(RedirectAttributes redirectAttributes, Trade trade, HttpServletRequest request) {
        try {
            if (trade == null) {
                redirectAttributes.addFlashAttribute("message", "请输入交易数据");
                return "redirect:/trade";
            }
            if (!StringUtils.isNotEmpty(trade.getCode())) {
                redirectAttributes.addFlashAttribute("message", "请输入股票代码");
                return "redirect:/trade";
            }
            Quote quote = stockService.getLastestQuoteByStock(trade.getCode());
            Stock stock = stockService.getByCode(trade.getCode());
            if (trade.getPrice() == null) {
                redirectAttributes.addFlashAttribute("message", "请输入股票交易金额");
                return "redirect:/trade";
            }
            if (trade.getPrice().compareTo(quote.getLowest()) <= 0) {
                redirectAttributes.addFlashAttribute("message", "股票交易金额不能小于最小值");
                return "redirect:/trade";
            }
            if (trade.getPrice().compareTo(quote.getHighest()) > 0) {
                redirectAttributes.addFlashAttribute("message", "股票交易金额大于最大值");
                return "redirect:/trade";
            }
            if (trade.getTradeCount() == null) {
                redirectAttributes.addFlashAttribute("message", "股票交易数量不能为空");
                return "redirect:/trade";
            }
            if (stock.getSurVolume() < trade.getTradeCount()) {
                redirectAttributes.addFlashAttribute("message", "股票发行量不足");
                return "redirect:/trade";
            }
            if (!StringUtils.isNotEmpty(trade.getType())) {
                trade.setType("S");
            }
            if (!StringUtils.isNotEmpty(trade.getTrader())) {
                trade.setTrader("SuperMan");
            }
            trade.setTradeTime(DateUtils.formatCurrentDate());
            redirectAttributes.addFlashAttribute("message", "交易成功");
            stockService.saveTrade(trade, quote, stock);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/trade";
        }
        return "redirect:/trade";
    }


    @RequestMapping(value = "getStock")
    @ResponseBody
    public Stock getStock(String code, String action) {
        Stock stock = stockService.getByCode(code);
        if (stock != null && StringUtils.equals(action, "MIN")) {
            Quote quote = stockService.getLastestQuoteByStock(code);
            quote.setPrice(stock.getPrice());
            if (quote != null) {
                stock.setQuote(quote);
            }
            List<Min> mins = stockService.getMins(code);
            if (mins.size() > 0) {
                stock.setMins(mins);
            }
        }
        return stock;
    }

    @RequestMapping(value = "ajax")
    @ResponseBody
    public Object ajax(String code) {
        Map<String, List<?>> map = new HashMap<String, List<?>>();
        map.put("stock", stockService.getAllStock());
        map.put("trader", stockService.getAllTraderOrderByCurrAmount());
        List<Trade> trades = stockService.getAllTradeByCode(code);
        if (trades.size() > 5) {
            trades = trades.subList(0, 4);
        }
        map.put("trade", trades);
        return map;
    }


}
